package com.example.boot.webservice.consumer.client;

import com.example.boot.webservice.provider.server.User;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;

public class BootWebServiceClient {

    private static final String URL = "http://localhost:9000/boot/webservice/provider/services/ws/api?wsdl";

    public static void main(String[] args) {
        BootWebServiceClient bootWebServiceClient = new BootWebServiceClient();
        System.out.println("bootWebServiceClient.get ---> " + bootWebServiceClient.get(1));
        User user = new User(null, "boot-webservice", 15);
        System.out.println("bootWebServiceClient.add ---> " + bootWebServiceClient.add(user));
    }

    public User add(User user) {
        return (User) invokeService(URL, "addUser", user);
    }

    public User get(Integer id) {
        return (User) invokeService(URL, "getUser", id);
    }

    private Object invokeService(String url, String method, Object... objects) {
        // 创建动态客户端
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        Client client = dcf.createClient(url);
        try {
            // invoke(方法名, 参数1, 参数2, 参数3....);
            // 注意如果是复杂参数的话，要保证复杂参数可以序列化
            return client.invoke(method, objects)[0];
        } catch (java.lang.Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
